# -*- coding: utf-8 *-*

#   This file is part of Sql-Rice.
#
#    Sql-Rice is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    Sql-Rice is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with Sql-Rice; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA


import sqlparse
import sqlparse.tokens as tokens
from string import Template


class Sentence(object):
#TODO: parsear subconsultas

    def __init__(self, sql='', **kwargs):
        '''Valid Key args  values are:
generate_update True | False
generate_insert True | False
generate_delete True | False'''
        self.sql = sql
        self.type = ''
        self.fields = []
        self.tables = []
        self.params = []
        self.update_query = ''
        self.insert_query = ''
        self.delete_query = ''
        if sql:
            parsed = sqlparse.parse(sql)
            stmnt = parsed[0]
            if stmnt.get_type() == u'SELECT':
                self.type = 'select'
                self._find_fields(stmnt)
                self._find_tables(stmnt)
                self._find_params(stmnt)
            if kwargs.get('generate_update', True):
                self.update_query = self._get_update_query()
            if kwargs.get('generate_insert', True):
                self.insert_query = self._get_insert_query()
            if kwargs.get('generate_delete', True):
                self.delete_query = self._get_delete_query()

    def _find_fields(self, statement):
        in_select = False
        for t in statement.flatten():
            if t.value.upper() == u'SELECT':
                in_select = True
            elif t.value.upper() == u'FROM':
                break
            elif in_select and t.ttype == tokens.Name:
                self.fields.append(t.value)

    def _find_tables(self, statement):
        in_from = False
        for t in statement.flatten():
            if t.value.upper() == u'FROM':
                in_from = True
            elif t.value.upper() in [u'WHERE', u'ORDER', u'GROUP']:
                break
            elif in_from and t.ttype == tokens.Name:
                self.tables.append(t.value)

    def _find_params(self, statement):
        for t in statement.flatten():
            if t.value.startswith(':'):
                value = t.value.replace(':', '', 1)
                self.params.append(value)
        self.params = list(set(self.params))

    def _get_update_query(self):
        t = Template('UPDATE ${table} SET ${fields} WHERE ${old_fields}')
        fields = ', '.join([f + '=:' + f for f in self.fields])
        old_fields = ' AND '.join([f + '=:old_' + f for f in self.fields])
        return t.substitute(table=self.tables[0], fields=fields,
                            old_fields=old_fields)

    def _get_insert_query(self):
        t = Template('INSERT INTO ${table}(${fields}) VALUES(${params})')
        fields = ', '.join(self.fields)
        params = ', '.join([':' + f for f in self.fields])
        return t.substitute(table=self.tables[0], fields=fields,
                            params=params)

    def _get_delete_query(self):
        t = Template('DELETE FROM ${table} WHERE ${params}')
        params = ' AND '.join([f + '=:' + f for f in self.fields])
        return t.substitute(table=self.tables[0], params=params)
